package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.vo.PacResultLevelImportVO;
import com.ruoyi.school.mapper.PacReslutLevel2Mapper;
import com.ruoyi.school.service.AcademicOutputService;
import com.ruoyi.school.mapper.ReslutLevelMapper;
import com.ruoyi.school.service.PacReslutLevel2Service;
import com.ruoyi.system.service.ReslutLevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author jeremylin
 * @description 针对表【reslut_level(学术成果等级)】的数据库操作Service实现
 * @createDate 2025-05-22 18:03:53
 */
@Service
public class ReslutLevelServiceImpl extends ServiceImpl<ReslutLevelMapper, PacReslutLevel>
        implements ReslutLevelService {

    @Resource
    private AcademicOutputService academicOutputService;

    @Resource
    private ReslutLevelMapper reslutLevelMapper;
    @Autowired
    private PacReslutLevel2Mapper pacReslutLevel2Mapper;

    @Resource
    private PacReslutLevel2Service pacReslutLevel2Service;

    @Override
    public List<PacReslutLevel> getList(PacReslutLevel rereslutLevel) {
        List<PacReslutLevel> list = lambdaQuery().list();
        return list;
    }

    /**
     * 获取详情
     *
     * @param rereslutLevel
     * @return
     */
    @Override
    public PacReslutLevel getDetails(PacReslutLevel rereslutLevel) {
        if (rereslutLevel.getId() == null) {
            throw new BaseException("id不能为空");
        }
        PacReslutLevel one = lambdaQuery().eq(PacReslutLevel::getId, rereslutLevel.getId()).one();
        return one;
    }

    /**
     * 新增数据
     *
     * @param rereslutLevel
     * @return
     */
    @Override
    public boolean add(PacReslutLevel rereslutLevel) {
        if (save(rereslutLevel)) {
            return true;
        }
        return false;
    }

    /**
     * 编辑数据
     *
     * @param rereslutLevel
     * @return
     */
    @Override
    public boolean edit(PacReslutLevel rereslutLevel) {
        if (updateById(rereslutLevel)) {
            return true;
        }
        return false;
    }

    /**
     * 删除数据
     * 1、删除的时候 需要先校验 改类型是否被其他的数据关联了，如果关联了，则不能删除
     *
     * @param rereslutLevel
     * @return
     */
    @Override
    public boolean delete(PacReslutLevel rereslutLevel) {
        int count = academicOutputService.countByLevel(rereslutLevel.getId());
        if (count > 0) {
            throw new BaseException("该等级被学术成果所关联，不能删除");
        }
        if (removeById(rereslutLevel)) {
            return true;
        }
        return false;
    }

    /**
     * 获取所有的成果等级
     *
     * @param rereslutLevel
     * @return
     */
    @Override
    public List<PacReslutLevel> getAllList(PacReslutLevel rereslutLevel) {
        List<PacReslutLevel> list = lambdaQuery().list();
        return list;
    }

    /**
     * 根据id找到
     *
     * @param resultTypeIds
     * @return
     */
    @Override
    public List<PacReslutLevel> selectByResultTypeIds(List<Long> resultTypeIds) {
        if (resultTypeIds.isEmpty()) {
            return new ArrayList<>();
        }
        List<PacReslutLevel> list = lambdaQuery().in(PacReslutLevel::getId, resultTypeIds).list();
        return list;
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @Override
    public List<PacResultLevelImportVO> getAll() {
        List<PacResultLevelImportVO> list = pacReslutLevel2Mapper.getAll();
        return list;
    }

    /**
     * 导入数据
     *
     * @param importVOS
     * @param operName
     * @return
     */
    @Transactional
    @Override
    public String importData(List<PacResultLevelImportVO> importVOS, String operName) {
        if (StringUtils.isNull(importVOS) || importVOS.size() == 0) {
            throw new ServiceException("导入竞赛数据不能为空！");
        }
        AtomicInteger successNum = new AtomicInteger();
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 先插入一级分类
        Map<String, PacResultLevelImportVO> uniqueMap = new HashMap<>();

        importVOS.forEach(item -> {
            uniqueMap.put(item.getResName(), item);
        });

        List<PacReslutLevel> pacReslutLevels = new ArrayList<>();
        uniqueMap.forEach((resName, item) -> {
            PacReslutLevel pacReslutLevel = new PacReslutLevel();
            pacReslutLevel.setResName(item.getResName());
            pacReslutLevel.setResLevel(item.getResLevel());
            pacReslutLevel.setResType(item.getResType());
            pacReslutLevel.setResLevel2("三等奖");
            if (item.getIsRk().equals("是")) {
                pacReslutLevel.setHightLevel(1);
            } else {
                pacReslutLevel.setHightLevel(0);
            }
            pacReslutLevels.add(pacReslutLevel);
        });

        saveBatch(pacReslutLevels);

        Map<String, PacReslutLevel> levelMap = pacReslutLevels.stream().collect(Collectors.toMap(PacReslutLevel::getResName, pacReslutLevel -> pacReslutLevel));
        // 插入子级分类
        List<PacReslutLevel2> PacReslutLevel2s = new ArrayList<>();
        importVOS.forEach(item -> {
            if (item.getResName2() != "" && item.getResName2() != null) {
                PacReslutLevel2 pacReslutLevel2 = new PacReslutLevel2();
                pacReslutLevel2.setResName(item.getResName2());
                PacReslutLevel pacReslutLevel = levelMap.get(item.getResName());
                pacReslutLevel2.setResLevelId(pacReslutLevel.getId().longValue());
                pacReslutLevel2.setResLevel(item.getResLevel());
                PacReslutLevel2s.add(pacReslutLevel2);
            }
        });

        pacReslutLevel2Service.saveBatch(PacReslutLevel2s);

//        if (failureNum > 0) {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new ServiceException(failureMsg.toString());
//        } else {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
        return successMsg.toString();
    }
}




